package com.alfayun.fiscalriskanalysis.security.customuserdetails;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.alfayun.fiscalriskanalysis.user.User;
import com.alfayun.fiscalriskanalysis.user.UserService;

public class CustomUserDetailsService implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userService.findUser(username);

		if (user == null) {
			throw new UsernameNotFoundException("username " + username + " not found");
		}
		
		Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
		
		if(user.role != null) {
			
			switch (user.role) {
			case ADMIN:
				authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
				break;
			case CLIENT:
				authorities.add(new SimpleGrantedAuthority("ROLE_CLIENT"));
				break;
			default:
				break;
			}
		}

		return new CustomUserDetails(user.getId(), user.username, user.password, authorities);
	}

}
